<script lang="ts" setup>
import { message } from 'ant-design-vue';
import ExcelJS from 'exceljs';
import index_add from './components/index_add.vue';
import { useUpload } from './useUpload';
import { useDownExcel } from './useDownExcel';
import { useExamData } from './useExamData';
import exam_add from './components/exam_add.vue';
// 获取数据
const year = ref<number>(0);
const loading = ref<boolean>(false);
const newData = ref<any[]>([]);
const data = ref<any[]>([]);
async function getData() {
  loading.value = true;
  data.value = [];
  await getAllExam().then((res: any) => {
    newData.value = res.data;
  }).catch(() => {
    loading.value = false;
  });
  data.value = await useExamData().getExamData(newData);
  year.value = Number.parseInt(newData.value[0].description, 10);
  loading.value = false;
}
onMounted(() => {
  getData();
});
// 新增
const visible = ref<boolean>(false);
const item = ref<any>({});
function add(id: number) {
  for (let i = 0; i < newData.value.length; i++) {
    if (id === newData.value[i].id) {
      item.value = {
        id: newData.value[i].id,
        examLevel: newData.value[i].examLevel,
        examDate: newData.value[i].examDate,
        registrationStartDate: newData.value[i].registrationStartDate,
        registrationDeadline: newData.value[i].registrationDeadline,
        description: newData.value[i].description,
      };
      break;
    }
  }
  getVisible();
}
function getVisible() {
  visible.value = !visible.value;
  getData();
}

// 删除单条
async function deleteItem(id: number) {
  await deleteExam(id).then(() => {
    message.success('删除成功！');
    getData();
  });
}

// 清空
async function clear() {
  await clearExamData().then(() => {
    getData();
  });
}

// excel文件上传
const fileList = ref<any>([]);

// 移除文件
function handleRemove(file: any) {
  const index = fileList.value.findIndex((f: { uid: any }) => f.uid === file.uid);
  fileList.value.splice(index, 1);
}

// 阻止自动上传
function beforeUpload(file: any) {
  fileList.value = [];
  fileList.value.push(file);
  return false; // 阻止自动上传
}

// 手动上传
async function handleManualUpload() {
  if (fileList.value.length === 0) {
    message.error('请上传文件！');
    return;
  }
  fileList.value.forEach(async (file: any) => {
    // 判断文件类型
    if (useUpload().checkIfExcel(file.name || '')) {
      // loading.value = true;
      const formData = new FormData();
      formData.append('file', file);
      const reader = new FileReader();
      reader.onload = async (e) => {
        const buffer: any = e.target?.result;
        if (buffer) {
          const workbook = new ExcelJS.Workbook();
          await workbook.xlsx.load(buffer).then(async () => {
            const worksheet: any = workbook.getWorksheet(1);
            const headers: any[] = [];
            const flag = useUpload().checkExamHeader(worksheet, headers);
            if (flag) {
              // 清空数据库
              await clear();
              // 上传到数据库
              await examFileupload(formData).then(() => {
                message.success('上传成功！');
                // 移除文件
                handleRemove(file);
                // 更新数据
                getData();
              })
                .catch(() => {
                  message.error('上传失败');
                  // 重新更新数据，将原先显示在页面的数据撤回
                  getData();
                });
            }
          });
        }
      };
      reader.readAsArrayBuffer(file);
    }
    else {
      message.error('请上传execl文件！');
    }
  });
}

// 表单
const visibleBM = ref<boolean>(false);

function showDrawer() {
  visibleBM.value = !visibleBM.value;
}

// 年份修改
const year_visible = ref<boolean>(false);
const newYear = ref<string>('');
const yearLoading = ref<boolean>(false);
function showModal() {
  year_visible.value = true;
}
function isFourDigitNumber(str: string): boolean {
  if (str.length !== 4) {
    return false;
  }
  const isNumeric = /^\d+$/.test(str);

  return isNumeric;
}
async function handleOk() {
  if (!isFourDigitNumber(newYear.value)) {
    message.error('输入的年份格式错误！');
    return;
  }
  yearLoading.value = true;
  for (let i = 0; i < newData.value.length; i++) {
    const examItem = {
      id: newData.value[i].id,
      examLevel: newData.value[i].examLevel,
      examDate: newData.value[i].examDate,
      registrationStartDate: newData.value[i].registrationStartDate,
      registrationDeadline: newData.value[i].registrationDeadline,
      examEvent: newData.value[i].examEvent,
      description: newYear.value,
    };
    await updateExam(examItem);
  }
  await getData();
  year.value = Number(newYear.value);
  yearLoading.value = false;
  year_visible.value = false;
}
</script>

<template>
  <PubPageMain class="max">
    <div class="header">
      <div class="left">
        <a-space>
          <div class="pjTitle">
            考情发布
          </div>
          <a-button type="link" @click="$router.push('/engineer_certification/index/exam_details')">
            查看报名信息
          </a-button>
          <a-button v-auth="'e-index-clear'" type="link" @click="getData()">
            刷新
          </a-button>
          <a-button v-auth="'e-index-clear'" type="link" @click="clear">
            清空
          </a-button>
        </a-space>
      </div>
      <div class="right">
        <a-space>
          <div class="add">
            <a-space>
              <a-upload
                v-auth="'e-index-upload'" :file-list="fileList" :before-upload="beforeUpload" name="file"
                :multiple="false" action="" accept=".xlsx, .xls" :on-remove="handleRemove"
              >
                <a-button>
                  <upload-outlined /> 点击选择文件
                </a-button>
              </a-upload>
              <a-button v-auth="'e-index-upload'" type="primary" @click="handleManualUpload">
                上传
              </a-button>
              <a-button v-auth="'e-index-upload'" type="primary" @click="useDownExcel().downExamExcel">
                下载模版
              </a-button>
              <a-button type="primary" @click="showDrawer">
                报名
              </a-button>
            </a-space>
          </div>
        </a-space>
      </div>
    </div>
    <exam_add :visible="visibleBM" :get-visible="showDrawer" />
    <div class="main">
      <a-list bordered :data-source="data" class="e-list" :loading="loading">
        <template #renderItem="{ item }">
          <a-list-item class="e-list-item">
            {{ item.str }}
            <span class="e-list-item-edit">
              <a-space>
                <FormOutlined v-auth="'e-index-edit'" @click="add(item.id)" />
                <DeleteOutlined v-auth="'e-index-delete'" @click="deleteItem(item.id)" />
              </a-space>
            </span>
          </a-list-item>
        </template>
        <template #header>
          <h2 class="e-list-header">
            研发工程师{{ year }}年时间安排
            <FormOutlined v-auth="'e-index-edit'" @click="showModal" />
          </h2>
        </template>
        <template #footer>
          <div class="e-list-footer">
            {{ year }}年通用能力考试排期如上表所示，若有新增考试场次，时间安排将另行通知
          </div>
        </template>
      </a-list>
    </div>
    <index_add
      v-if="visible" class="index-add" :visible="visible" :get-visible="getVisible" :item="item"
      :year="year"
    />
    <a-modal v-model:visible="year_visible" title="修改年份" :confirm-loading="yearLoading" @ok="handleOk">
      <a-input v-model:value="newYear" placeholder="请输入年份（例：2024）" />
    </a-modal>
  </PubPageMain>
</template>

<style lang="scss" scoped>
.max {
  display: flex;
  flex-direction: column;
  max-width: 100%;
  max-height: 95%;
  overflow: auto;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: 31px;
    margin-bottom: 10px;

    .pjTitle {
      padding-left: 15px;
      background: url("@/assets/images/title-left-bg.svg") no-repeat;
    }

    .right {
      display: flex;
      align-items: center;
    }
  }

  .main {
    display: flex;
    justify-content: center;
    width: 100%;
    height: 95%;
    // max-height: 65vh;
    overflow: auto;
    text-align: center;

    .e-list {
      width: 70%;
      max-height: 65vh;
      overflow-y: auto;

      .e-list-item {
        display: flex;
        justify-content: center;

        .e-list-item-edit {
          margin-left: 20px;
          color: #1677ff;
        }
      }

      .e-list-footer {
        font-size: 15px;
        font-weight: bolder;
        color: red;
      }
    }
  }
}

.ant-upload-wrapper {
  display: flex;
  flex-direction: row-reverse;
  align-items: center;
  height: 31px;
}
</style>
